package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.Valid;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.user.User;
import com.handu.luna.core.domain.user.User.UserStatus;
import com.handu.luna.core.domain.user.UserRank;

@Controller
@RequestMapping("/user/*")
public class UserController extends BaseController {
	
	@RequestMapping()
    public BossModel list(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		if(viewState == null || viewState.equals("")){
			return createModel("user/list").add("usersPage",context.getUserRepository().findAll(User.nameLike(viewState), pageable)).add("viewState", "");

		}else{
			return createModel("user/list").add("usersPage",context.getUserRepository().findAll(User.nameLike(viewState), pageable)).add("viewState", viewState);
		}
	}


	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		LinkedList<UserRank> userRank = new LinkedList<UserRank>(context.getUserRankRepository().findAllSpecial());
		UserRank ur = new UserRank();
		ur.setId(0l);
		ur.setRankName("普通会员");
		userRank.add(0,ur);
		return createModel("user/info").add("user",context.getUserRepository().findOne(id)).add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	@InitBinder(value={"name","email","userRank","userSex","userBirthday","mobile","status"})
	public BossModel save(@Valid final User user, final BindingResult bindingResult,String inputPassword, final ModelMap model, RedirectAttributes redirectAttributes,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		LinkedList<UserRank> userRank = new LinkedList<UserRank>(context.getUserRankRepository().findAllSpecial());
		UserRank ur = new UserRank();
		ur.setId(0l);
		ur.setRankName("普通会员");
		userRank.add(0,ur);
		if (bindingResult.hasErrors()) {
			return createModel("user/info").add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
		}
		String message;
		List<User> userNameCheck;
		List<User> userEmailCheck;
		List<User> userMobileCheck;
		if(user.getId() == null){
			if(inputPassword.equals("") || inputPassword.length() < 6 || inputPassword.length() > 20){
				bindingResult.addError(new FieldError("user", "password", "密码6-20位字母、数字和特殊符号构成，区分大小写。"));
				return createModel("user/info").add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
			}
			user.setPassword(inputPassword);
			user.setIsEmailCheck("否");
			user.setIsMobileCheck("否");
			userNameCheck = context.getUserRepository().findByName(user.getName());
			userEmailCheck = context.getUserRepository().findByEmail(user.getEmail());
			userMobileCheck = context.getUserRepository().findByMobile(user.getMobile());
		}else{
			if(inputPassword != "" && inputPassword.length() >= 6 && inputPassword.length() <= 20){
				user.setPassword(inputPassword);
			}else if(inputPassword != "" && (inputPassword.length() < 6 || inputPassword.length() > 20)){
				bindingResult.addError(new FieldError("user", "password", "密码6-20位字母、数字和特殊符号构成，区分大小写。"));
				return createModel("user/info").add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
			}
			userNameCheck = context.getUserRepository().findByNameAndId(user.getName(),user.getId());
			userEmailCheck = context.getUserRepository().findByEmailAndId(user.getEmail(),user.getId());
			userMobileCheck = context.getUserRepository().findByMobileAndId(user.getMobile(),user.getId());
		}
		
		
		if(!userNameCheck.isEmpty()){
			message = "会员名" + user.getName() + "已存在";
			bindingResult.addError(new FieldError("user", "name", message));
			return createModel("user/info").add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
		}else if(!userEmailCheck.isEmpty()){
			message = user.getEmail() + "已存在";
			bindingResult.addError(new FieldError("user", "email", message));
			return createModel("user/info").add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
		}else if(!userMobileCheck.isEmpty()){
			message = "手机号" + user.getMobile() + "已存在";
			bindingResult.addError(new FieldError("user", "mobile", message));
			return createModel("user/info").add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
		}else{
			String messagePrefix = user.getSucessFlashMessage();
			context.getUserRepository().save(user);
			
			String salt = createRandom();
			String token = AES(user.getId() + salt,
					user.getId() + salt);
			user.setPasswordSalt(salt);
			user.setPassword(SHA256Encrypt(user.getPassword() + user.getId()
					+ salt + token));
			
			context.getUserRepository().save(user);
			return createModel("user/list").add("usersPage",context.getUserRepository().findAll(pageable)).add("viewState","").add("message", messagePrefix);
		}	
	}
	
	@RequestMapping(value="add")
	public BossModel add(){
		User user = new User();
		user.setUserSex("0");
		user.setIsEmailCheck("否");
		user.setIsMobileCheck("否");
		user.setLevelPoint(0);
		user.setConsumePoint(0);
		user.setStatus(UserStatus.NORMAL);
		LinkedList<UserRank> userRank = new LinkedList<UserRank>(context.getUserRankRepository().findAllSpecial());
		UserRank ur = new UserRank();
		ur.setId(0l);
		ur.setRankName("普通会员");
		userRank.add(0,ur);
		return createModel("user/info").add("user",user).add("userStatus", User.UserStatus.values()).add("userRanks", userRank);
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){

		context.getUserRepository().delete(id);
		return createModel("user/users_table")
				.add("usersPage",context.getUserRepository().findAll(User.nameLike(viewState), pageable))
				.add("viewState", viewState);
	}
	
	/**
	 * 生成六位随机数
	 * 
	 * @param email
	 */
	private String createRandom() {
		int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		Random rand = new Random();
		for (int i = 10; i > 1; i--) {
			int index = rand.nextInt(i);
			int tmp = array[index];
			array[index] = array[i - 1];
			array[i - 1] = tmp;
		}
		int result = 0;
		for (int i = 0; i < 6; i++)
			result = result * 10 + array[i];
		return String.valueOf(result);
		// System.err.println(result);
	}

	/**
	 * 使用SHA-256 算法 加密，默认模式 AES/ECB
	 */

	public static String SHA256Encrypt(String orignal) {
		String ALGORITHM = "SHA-256";
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance(ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		if (null != md) {
			byte[] origBytes = orignal.getBytes();
			md.update(origBytes);
			byte[] digestRes = md.digest();
			String digestStr = getDigestStr(digestRes);
			System.err.println(digestStr);
			return digestStr;
		}

		return null;
	}

	private static String getDigestStr(byte[] origBytes) {
		String tempStr = null;
		StringBuilder stb = new StringBuilder();
		for (int i = 0; i < origBytes.length; i++) {
			tempStr = Integer.toHexString(origBytes[i] & 0xff);
			if (tempStr.length() == 1) {
				stb.append("0");
			}
			stb.append(tempStr);

		}
		return stb.toString();
	}

	/**
	 * 使用AES 算法 加密，默认模式 AES/ECB
	 */
	public static String AES(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return parseByte2HexStr(result); // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String parseByte2HexStr(byte buf[]) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}
	
}
